<template>
  <div>
    <el-card class="box-card" :body-style="{ padding: '18px 0', boxSizing: 'border-box' }">
      <div slot="header" class="clearfix">
        <el-row>
          <el-col :lg="16" :sm="16" :xl="16">
            <el-date-picker
              v-model="aimDate"
              :picker-options="pickerOptions0"
              @change="chooseDate"
              type="date"
              placeholder="选择日期"
              style="width: 100% !important"
            >
            </el-date-picker>
          </el-col>
          <el-col :lg="4" :sm="4" :xl="4" class="fr">
            <i class="el-icon-edit icon" @click="showYearGoal()"></i>
          </el-col>
        </el-row>
      </div>
      <div class="border_bottom pb10">
        <el-row>
          <el-col :lg="24" :sm="12" :xs="12" class="tac">
            <div class="main_title">
              年度目标：<strong class="main_title">{{ annualTarget | formatMoney }}</strong>
            </div>
          </el-col>
        </el-row>
      </div>
      <div class="border_bottom pt10 pb10">
        <el-row>
          <el-col :lg="8" :sm="8" :xs="8" class="tar">
            <div class="subtitle line">目前完成</div>
            <div class="subtitle line">预计完成</div>
            <div class="subtitle line">每天需完成</div>
          </el-col>
          <el-col :lg="6" :sm="6" :xs="6" :offset="2" class="tac">
            <div class="main_title border_bottom line">
              {{ annualFinish | formatMoney }}
            </div>
            <div class="main_title border_bottom line">{{ yearAble | formatMoney }}</div>
            <div class="main_title border_bottom line">
              {{ annualLastAverage | formatMoney }}
            </div>
          </el-col>
          <el-col :lg="6" :sm="6" :xs="6" :offset="2" class="tac">
            <div class="main_title border_bottom line">
              {{ ((annualFinish / annualTarget) * 100).toFixed(0) + '%' }}
            </div>
            <div class="main_title border_bottom line">
              {{ ((yearAble / annualTarget) * 100).toFixed(0) + '%' }}
            </div>
            <div class="main_title border_bottom line">余{{ annualLastDay }}天</div>
          </el-col>
        </el-row>
      </div>
      <div class="border_bottom pt10 pb10">
        <el-row>
          <el-col :lg="24" :sm="12" :xs="12" class="tac">
            <div class="main_title">
              {{ nowMonth }}目标：<strong class="main_title">{{ monthTarget | formatMoney }}</strong>
            </div>
          </el-col>
        </el-row>
      </div>
      <div class="border_bottom pt10 pb10">
        <el-row>
          <el-col :lg="8" :sm="8" :xs="8" class="tar">
            <div class="subtitle line">目前完成</div>
            <div class="subtitle line">预计完成</div>
            <div class="subtitle line">每天需完成</div>
          </el-col>
          <el-col :lg="6" :sm="6" :xs="6" :offset="2" class="tac">
            <div class="main_title border_bottom line">{{ monthFinish | formatMoney }}</div>
            <div class="main_title border_bottom line">{{ monthAble | formatMoney }}</div>
            <div class="main_title border_bottom line">
              {{ monthLastAverage | formatMoney }}
            </div>
          </el-col>
          <el-col :lg="6" :sm="6" :xs="6" :offset="2" class="tac">
            <div class="main_title border_bottom line">
              {{ ((monthFinish / monthTarget) * 100).toFixed(0) + '%' }}
            </div>
            <div class="main_title border_bottom line">
              {{ ((monthAble / monthTarget) * 100).toFixed(0) + '%' }}
            </div>
            <div class="main_title border_bottom line">余{{ monthLastDay }}天</div>
          </el-col>
        </el-row>
      </div>
    </el-card>
    <!-- 编辑 -->
    <el-dialog
      :modal-append-to-body="false"
      :top="userAgent ? '60px' : '15vh'"
      title="目标设置"
      :visible.sync="dialogVisible1"
      :width="dialogWidth"
      :before-close="beforeClose"
    >
      <div class="wid-100">
        <el-form class="wid-100" label-width="80px" inline>
          <el-form-item label="选择年份">
            <el-select v-model="selectedYear" @change="chooseYear">
              <el-option :label="item.label" :value="item.value" :selected="item.select" v-for="item in yearList" :key="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="年度目标">
            <el-input v-model="annualAmount.goal" @input="changeInput"></el-input>
          </el-form-item>
          <hr style="margin-bottom: 20px" />
          <!-- 每月目标 -->
          <el-form-item v-for="item in monthList" :label="item.date + '月目标'" :key="item.date">
            <el-input v-model="item.goal" :value="item.goal" @input="changeInput"> </el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="beforeClose" size="small">关闭</el-button>
        <el-button type="primary" @click="setYearGoal" size="small" :loading="btnLoading" :disabled="btnDisabled">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      aimDate: new Date().toISOString().substr(0, 10),
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 24 * 60 * 60 * 1000; //不可以选择今天之后的日期
        },
      },
      preDay: new Date().toISOString().substr(0, 10),
      //选的当年第一天
      year_s: new Date().toISOString().substr(0, 10),
      year_e: new Date().toISOString().substr(0, 10),
      //选的当月第一天
      month_s: new Date().toISOString().substr(0, 10),
      month_e: new Date().toISOString().substr(0, 10),
      nowMonth: 1,
      selectedYear: '2020',
      yearList: [
        { label: '2020年目标', value: '2020', select: true },
        { label: '2021年目标', value: '2021', select: false },
        { label: '2022年目标', value: '2022', select: false },
      ],
      monthList: [
        { goal: 0, unit: 'month', date: '01' },
        { goal: 0, unit: 'month', date: '02' },
        { goal: 0, unit: 'month', date: '03' },
        { goal: 0, unit: 'month', date: '04' },
        { goal: 0, unit: 'month', date: '05' },
        { goal: 0, unit: 'month', date: '06' },
        { goal: 0, unit: 'month', date: '07' },
        { goal: 0, unit: 'month', date: '08' },
        { goal: 0, unit: 'month', date: '09' },
        { goal: 0, unit: 'month', date: '10' },
        { goal: 0, unit: 'month', date: '11' },
        { goal: 0, unit: 'month', date: '12' },
      ],
      annualAmount: { date: '01', goal: '', unit: 'year' },
      yearGoal: [],
      selectWay: 'num',
      annualTarget: 0,
      annualFinish: 0,
      annualLastDay: 0,
      //annualPercent:'0%',
      //annualLastPercent:'0%',
      //annualLastAverage:0,
      monthTarget: 0,
      monthFinish: 0,
      monthLastDay: 0,
      //monthPercent:'0%',
      //monthLastPercent:'0%',
      //monthLastAverage:0,
      //monthAble:0,
      //yearAble:0,
      dialogVisible1: false,
      dialogWidth: 0,
      submit: true,
      selectNum: true,
      selectPercent: false,
      selectAverage: false,
      // 确认按钮
      btnLoading: false,
      btnDisabled: false,
      seeDetailStatus: true,
    };
  },
  //computed是计算属性，也就是依赖其它的属性计算所得出最后的值
  //vuex的状态值在这边操作
  computed: {
    annualPercent() {
      //console.log(this.annualTarget==0)
      if (this.annualTarget == 0) {
        return 0;
      } else {
        return ((this.annualFinish / this.annualTarget) * 100).toFixed(0) + '%';
      }
    },
    annualLastPercent() {
      if (this.annualTarget == 0) {
        return 0;
      } else {
        return ((this.annualFinish / this.annualTarget) * 100 - 100).toFixed(0) + '%';
      }
    },
    annualLastAverage() {
      if (this.annualTarget == 0) {
        return 0;
      } else {
        return ((this.annualTarget - this.annualFinish) / this.annualLastDay).toFixed(0);
      }
    },
    monthPercent() {
      if (this.monthTarget == 0) {
        return 0;
      } else {
        return ((this.monthFinish / this.monthTarget) * 100).toFixed(0) + '%';
      }
    },
    monthLastPercent() {
      if (this.monthTarget == 0) {
        return 0;
      } else {
        return ((this.monthFinish / this.monthTarget) * 100 - 100).toFixed(0) + '%';
      }
    },
    monthLastAverage() {
      if (this.monthTarget == 0) {
        return 0;
      } else {
        return ((this.monthTarget - this.monthFinish) / this.monthLastDay).toFixed(0);
      }
    },
    monthAble() {
      var date = new Date(this.aimDate);
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      var days;
      //获取当前月天数
      if (month == 2) {
        days = year % 4 == 0 ? 29 : 28;
      } else if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
        //月份为：1,3,5,7,8,10,12 时，为大月.则天数为31；
        days = 31;
      } else {
        //其他月份，天数为：30.
        days = 30;
      }
      return (this.monthFinish / day).toFixed(0) * days;
    },
    yearAble(getAnnualLastDay) {
      var date = new Date(this.aimDate);
      var year = date.getFullYear();
      var days = year % 4 == 0 ? 366 : 365;
      var day = days - this.annualLastDay;
      return (this.annualFinish / day).toFixed(0) * days;
    },
  },
  created() {
    this.setDialogWidth();
  },
  mounted() {
    //默认显示前一天日期
    var now = new Date();
    var sDay = new Date(now.getTime() - 24 * 3600 * 1000);
    var syear = sDay.getFullYear();
    var smonth = sDay.getMonth() + 1 < 10 ? '0' + (sDay.getMonth() + 1) : sDay.getMonth() + 1;
    var sday = sDay.getDate() < 10 ? '0' + sDay.getDate() : sDay.getDate();

    this.aimDate = syear + '-' + smonth + '-' + sday;
    this.preDay = syear + '-' + smonth + '-' + sday;
    this.year_s = syear + '-01-01';
    this.year_e = syear + '-12-31';
    this.month_s = syear + '-' + smonth + '-01';
    var day = new Date(syear, smonth, 0);
    this.month_e = syear + '-' + smonth + '-' + day.getDate();
    this.nowMonth = smonth;

    this.getAnnualLastDay();
    this.getMonthLastDay();
    this.getGoal();
    this.getIncome();
    window.onresize = () => {
      return (() => {
        this.setDialogWidth();
      })();
    };
  },
  methods: {
    setDialogWidth() {
      //console.log(document.body.clientWidth)
      var val = document.body.clientWidth;
      const def = 660; // 默认宽度
      if (val < def) {
        this.dialogWidth = '100%';
      } else {
        this.dialogWidth = def + 'px';
      }
    },
    //选择切换日期
    chooseDate: function () {
      //关闭日期选框
      var date = new Date(this.aimDate);
      var year = date.getFullYear();
      var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
      this.nowMonth = month;
      var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
      this.aimDate = year + '-' + month + '-' + day;
      //当年第一天
      this.year_s = year + '-01-01';
      //当年最后一天
      this.year_e = year + '-12-31';
      //当月第一天
      this.month_s = year + '-' + month + '-01';
      //当月最后一天
      var day = new Date(year, month, 0);
      this.month_e = year + '-' + month + '-' + day.getDate();
      //this.aimDate = year + "-" + month + "-" + day
      this.getAnnualLastDay();
      this.getMonthLastDay();
      this.getGoal();
      this.getIncome();
    },
    //设置查看全年目标
    showYearGoal(e, item) {
      this.dialogVisible1 = true;
      this.getYearGoal();
    },
    //设置目标里选择年份
    chooseYear: function () {
      this.getYearGoal();
    },
    //计算选的日期当前年剩余天数
    getAnnualLastDay: function () {
      var date = new Date(this.aimDate);
      var year = date.getFullYear();
      var date2 = new Date(year, 11, 30, 23, 59, 59, 999); //
      //转换成秒
      var time = (date2 - date) / 1000;
      this.annualLastDay = Math.floor(time / (24 * 60 * 60));
    },
    //计算选的日期当前月剩余天数
    getMonthLastDay: function () {
      var date = new Date(this.aimDate);
      var month = date.getMonth() + 1;
      var day = date.getDate();
      //当月份为二月时，根据闰年还是非闰年判断天数
      if (month == 2) {
        this.monthLastDay = year % 4 == 0 ? 29 - day : 28 - day;
      } else if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
        //月份为：1,3,5,7,8,10,12 时，为大月.则天数为31；
        this.monthLastDay = 31 - day;
      } else {
        //其他月份，天数为：30.
        this.monthLastDay = 30 - day;
      }
    },
    // 平台目标
    getGoal: async function () {
      //查询当前年度目标
      await this.$api
        .platformGoal({
          date_s: this.year_s,
          date_e: this.year_e,
          unit: 'year',
        })
        .then(res => {
          if (res.code == 101) {
            var self = this;
            res.data.forEach(function (obj, i) {
              if (obj.unit == 'year') {
                //console.log(obj.goal);
                self.annualTarget = obj.goal;
              }
            });
          }
        });
      //查询当前月度目标
      await this.$api
        .platformGoal({
          date_s: this.month_s,
          date_e: this.month_e,
        })
        .then(res => {
          if (res.code == 101) {
            var self = this;
            res.data.forEach(function (obj, i) {
              if (obj.unit == 'month') {
                //console.log(obj.goal);
                self.monthTarget = obj.goal;
              }
            });
          }
        });
    },
    // 目标设置查询平台年度目标及各月份目标
    getYearGoal: async function () {
      //console.log(this.selectedYear);
      var year_s = this.selectedYear + '-01-01';
      var year_e = this.selectedYear + '-12-31';
      await this.$api
        .platformGoal({
          date_s: year_s,
          date_e: year_e,
        })
        .then(res => {
          if (res.code == 101) {
            //console.log(res.data);
            var self = this;
            //初始化为0
            self.annualAmount.goal = 0;
            this.monthList.forEach(function (obj, i) {
              obj.goal = 0;
            });
            res.data.forEach(function (obj, i) {
              if (obj.unit == 'year') {
                //console.log(obj.goal);
                self.annualAmount.goal = obj.goal;
              }
              if (obj.unit == 'month') {
                //console.log(obj.month-1);
                self.monthList[obj.month - 1].goal = obj.goal;
              }
            });
          }
        });
    },
    // 目标设置提交
    setYearGoal: async function () {
      this.btnLoading = true;
      this.yearGoal = [];
      this.yearGoal = this.monthList.concat(this.annualAmount);
      this.yearGoal = this.deepCopy(this.yearGoal);
      //过滤有输入目标值的yearGoal
      this.yearGoal = this.yearGoal.filter(item => {
        return item.goal != '';
      });
      var self = this;
      const regNum = /^\+?[1-9][0-9]*$/;
      this.yearGoal.forEach(function (obj, i) {
        //          console.log(obj.date);
        if (!regNum.test(obj.goal)) {
          this.$message.warning('请输入正整数~');
          self.submit = false;
        }
        obj.date = self.selectedYear + '-' + obj.date + '-01';
      });
      //console.log(this.yearGoal );
      //console.log(this.submit);
      if (this.submit) {
        await this.$api
          .setGoal({
            batch_str: this.yearGoal,
          })
          .then(res => {
            if (res.code == 101) {
              this.btnLoading = false;
              this.$message.success('提交成功~');
              this.dialogVisible1 = false;
              this.getGoal();
              this.getIncome();
            }
          });
      }
    },
    deepCopy(obj) {
      //数组的深拷贝
      let temp = obj.constructor === Array ? [] : {};
      for (let val in obj) {
        temp[val] = typeof obj[val] == 'object' ? this.deepCopy(obj[val]) : obj[val];
      }
      return temp;
    },
    // 平台流水
    getIncome: async function () {
      //console.log(this.aimDate);
      //查询当前年目前完成
      await this.$api
        .platformIncome({
          date_s: this.year_s,
          date_e: this.aimDate,
        })
        .then(res => {
          if (res.code == 101) {
            this.annualFinish = (res.data.income * 1).toFixed(0) * 1;
            //console.log(res.data);
          }
        });
      //查询当前月完成
      await this.$api
        .platformIncome({
          date_s: this.month_s,
          date_e: this.aimDate,
        })
        .then(res => {
          if (res.code == 101) {
            this.monthFinish = res.data.income;
            //console.log(res.data);
          }
        });
    },
    // 目标设置输入框输入值时改变状态
    changeInput() {
      this.seeDetailStatus = false;
      //console.log(this.seeDetailStatus);
    },
    beforeClose() {
      //console.log(this.seeDetailStatus);
      // 如果只是查看详情
      if (this.seeDetailStatus) {
        this.dialogVisible1 = false;
        return;
      }
      this.$confirm('关闭后将不会保存数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.dialogVisible1 = false;
          this.seeDetailStatus = true;
        })
        .catch(() => {});
    },
  },
};
</script>
<style lang='stylus' scoped>
body {
}

.icon {
  font-size: 26px;
  margin: 6px 0 0 20px;
  cursor: pointer;
}

.main_title {
  height: 24px;
  line-height: 24px;
  font-size: 16px;
}

.title {
  height: 24px;
  line-height: 24px;
  font-size: 14px;
}

.subtitle {
  font-size: 14px;
}

.border_bottom {
  border-bottom: 1px solid #eeecec;
}

.line {
  height: 40px;
  line-height: 40px;
}
</style>
